package com.aaa.security;

import com.aaa.entity.Emp;
import com.aaa.entity.Role;
import com.aaa.service.EmpService;
import com.aaa.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.List;

/**
 * 获取用户信息
 */
@Repository
public class UserDetailsServiceImpl implements UserDetailsService {
    @Resource
    EmpService empService;

    @Resource
    RoleService roleService;

    /**
     * 根据用户名获取用户信息
     * @param s：表单提交的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        System.out.println("s:"+s);

        QueryWrapper<Emp> empQueryWrapper=new QueryWrapper<>();
        empQueryWrapper.eq("eusername",s);
        List<Emp> list = empService.list(empQueryWrapper);
        System.out.println(list.size());
        if(list.size()>0){
            Emp emp=list.get(0);
            System.out.println(emp);
            //查询用户的角色
            Role role = roleService.getById(emp.getRid());
            StringBuffer str=new StringBuffer();
            str.append(role.getRolename());

            //设置权限
            if(s.equals("hzj")){
                //将字符串按照逗号分隔，转换为权限列表
                //ROLE_开头的是角色（可以有多个），后面的add,update......是权限(可以有多个)
                str.append(",insert,update,select");
            }else{
                str.append(",select");
            }
            emp.setAuthorties(AuthorityUtils.commaSeparatedStringToAuthorityList(str.toString()));
            //System.out.println(emp);
            //return emp;
            return list.get(0);
        }else {
            throw new UsernameNotFoundException("用户名不存在");
        }
    }
}
